package mygang.security;

import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mygang.helper.JsonHelper;
import mygang.model.BaseModel;
import mygang.model.CustomResponse;
import mygang.model.UserWrapper;
import mygang.singleton.Statistic;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

/**
 *
 * @author Volodymyr Lavrynovych <volodya.lavrynovych@gmail.com>
 * date: 08/08/2012
 */
public class CustomLogoutHandler extends BaseModel implements LogoutSuccessHandler {

    @Resource(name="sessionRegistry")
    private SessionRegistryImpl sessionRegistry;
    
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        
        Object principal = authentication.getPrincipal();
        if(principal!=null && principal instanceof UserWrapper){
            Statistic.getInstance().users.remove((UserWrapper)principal);
        }
        
        CustomResponse result = new CustomResponse(
                CustomResponse.Result.SUCCESS, 
                "", 
                "You have been successfully Logged Out.", 
                "Bye-Bye");
        
        JsonHelper.prepareJsonResponse(result, response);
    }

}